package com.yizhe.controller;

import com.yizhe.domain.LoginRecodes;
import com.yizhe.domain.UserInfo;
import com.yizhe.service.LoginRecodesService;
import com.yizhe.service.UserInfoService;
import com.yizhe.utils.EncryptUtilsV2;
import com.yizhe.utils.HttpSender;
import com.yizhe.utils.PhoneUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * 
 * 
 * @author fangchao
 * 
 */
@Controller
@RequestMapping("/user")
public class UserController {

	@Resource
	private UserInfoService userInfoService;

	@Resource
	private LoginRecodesService loginRecodesService;

	@RequestMapping("registerPage")
	public String index() {
		return "register";
	}
	
	@RequestMapping("loginPage")
	public String loginPage() {
		return "login";
	}
	
	@RequestMapping("indexPage")
	public String indexPage(Model model,HttpServletRequest request) {
		HttpSession session = request.getSession();
		UserInfo userInfo = (UserInfo)session.getAttribute(Constants.USER_INFO);
		LoginRecodes loginRecodes = new LoginRecodes();
		loginRecodes.setUserId(userInfo.getId());
		loginRecodes = loginRecodesService.getLastLoginRecodes(loginRecodes);
		model.addAttribute("userInfo", userInfo);
		model.addAttribute("loginRecodes", loginRecodes);
		return "index";
	}
	
	@RequestMapping("resetPasswordPage")
	public String resetPasswordPage() {
		return "resetPassword";
	}

	/**
	 * 注册方法
	 *
	 * @return
	 */
	@RequestMapping("register")
	@ResponseBody
	public Map<String, Object> register(HttpServletRequest request, @ModelAttribute UserInfo entity) {
		Map<String, Object> map = new HashMap<String, Object>();
        HttpSession session = request.getSession(true);
        String verifyCodeSession = session.getAttribute("rand") == null ? "" : session.getAttribute("rand").toString();
		try {
			String mobile = entity.getMobile();
			String verifyCode = entity.getVerifyCode();
			String sms_code_message = Constants.USER_MESSAGE.get(mobile);
			if (!StringUtils.hasText(sms_code_message)) {
				map.put("code", 0);
				map.put("message", "短信验证码已经过期，请重新输入");
				return map;
			}
			if (!StringUtils.hasText(verifyCode)) {
				map.put("code", 0);
				map.put("message", "请确认验证码");
				return map;
			}
			if (!verifyCodeSession.equals(verifyCode)) {
				map.put("code", 0);
				map.put("message", "验证码不正确，请重新输入");
				return map;
			}
			UserInfo userInfo = new UserInfo();
			userInfo.setMobile(mobile);
			int count = (int) userInfoService.selectUserInfoCount(userInfo);
			if (count != 0) {
				map.put("code", 0);
				map.put("message", "您的手机号码已经注册过");
				return map;
			}
			entity.setPassword(EncryptUtilsV2.MD5Encode(entity.getPassword()));
			entity.setCreateTime(new Date());
			int updateCount = userInfoService.saveUserInfo(entity);
			if(updateCount > 0) {
				map.put("code", 200);
				map.put("message", "注册成功");
			} else {
				map.put("code", 0);
				map.put("message", "注册失败");
			}
			Constants.USER_MESSAGE.clear();
			System.out.println(map.get("message"));
		} catch (Exception e) {
			e.printStackTrace();
			map.put("code", 0);
			map.put("message", "保存失败，请联系管理员");
		}
		return map;
	}
	
	/**
	 * 发送验证码：
	 * 参数：mobile:手机号，verifyCode：验证码
	 * 
	 * @return
	 */
	@RequestMapping("sendSms")
	@ResponseBody
	public Map<String, Object> sendSms(@ModelAttribute UserInfo user) {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			String mobile = user.getMobile();
			if (!StringUtils.hasText(mobile)) {
				map.put("code", 0);
				map.put("message", "短信获取失败,请输入手机号码.");
				return map;
			}
			if (!PhoneUtil.isMobileNO(mobile)) {
				map.put("code", 0);
				map.put("message", "短信获取失败,请输入正确的手机号码.");
				return map;
			}
			String result = getString(5);
            String url = "http://sapi.253.com/msg/";// 应用地址
    		String account = "yaw_10";// 账号
    		String pswd = "4Sniywhx9";// 密码
    		String mobileNo = mobile;// 手机号码，多个号码使用","分割
    		String msg = "【一折】验证码：" + result;// 短信内容
    		boolean needstatus = true;// 是否需要状态报告，需要true，不需要false
    		String extno = null;// 扩展码
    		String returnString = HttpSender.batchSend(url, account, pswd, mobileNo, msg, needstatus, extno);
            if ("0".equals(returnString.split(",")[1].substring(0,1))) {
				Constants.USER_MESSAGE.put(mobile, result);
				map.put("verify_code", result);
				map.put("code", 200);
				return map;
			} else {
				map.put("code", 0);
				Constants.USER_MESSAGE.put(mobile, result);
				map.put("verify_code", result);
				map.put("message", "短信获取失败,请联系管理员.");
				return map;
			}
		} catch (Exception e) {
			e.printStackTrace();
			map.put("code", 0);
			map.put("message", "短信获取失败,请联系管理员.");
		}
		return map;
	}
	
	public static String getString(int length) {
		StringBuffer buffer = new StringBuffer("0123456789");
		StringBuffer sb = new StringBuffer();
		Random random = new Random();
		int range = buffer.length();
		for (int i = 0; i < length; i++) {
			sb.append(buffer.charAt(random.nextInt(range)));
		}
		return sb.toString();
	}
	
	/**
	 * 登录
	 * @param model
	 * @param user
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("login")
	@ResponseBody
	public Map<String, Object> login(Model model, @ModelAttribute UserInfo user,
			HttpServletRequest request) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		String password = user.getPassword();
		String verifyCode = user.getVerifyCode();
		HttpSession session = request.getSession(true);
		if (!verifyCode.equalsIgnoreCase((String) session.getAttribute("rand"))) {
			map.put("code", 0);
			map.put("message", "验证码不正确，请重新输入");
			return map;
		}
		UserInfo userInfo = new UserInfo();
		userInfo.setMobile(user.getMobile());
		userInfo = userInfoService.selectUserInfo(userInfo);
		if(userInfo == null){
			map.put("code", 0);
			map.put("message", "用户不存在");
			return map;
		}
		if(!userInfo.getPassword().equals(EncryptUtilsV2.MD5Encode(password))){
			map.put("code", 0);
			map.put("message", "密码错误");
			return map;
		}
		if(userInfo.getStatus() !=0 ){
			map.put("code", 0);
			map.put("message", "用户被冻结，请联系管理员");
			return map;
		}
		session.setAttribute(Constants.USER_INFO, userInfo);
		map.put("code", 200);
		map.put("message", "登录成功");
		LoginRecodes loginRecodes = new LoginRecodes();
		loginRecodes.setUserId(userInfo.getId());
		loginRecodes.setLoginTime(new Date());
		loginRecodes.setLoginIp(request.getRemoteAddr());
		loginRecodesService.saveLoginRecodes(loginRecodes);
		return map;
	}
	
	/**
	 * 客户端登录
	 * @param model
	 * @param user
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("clientLogin")
	@ResponseBody
	public Map<String, Object> clientLogin(Model model, @ModelAttribute UserInfo user,
			HttpServletRequest request) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		String password = user.getPassword();
		UserInfo userInfo = new UserInfo();
		userInfo.setMobile(user.getMobile());
		userInfo = userInfoService.selectUserInfo(userInfo);
		if(userInfo == null){
			map.put("code", 0);
			map.put("message", "用户不存在");
			return map;
		}
		if(!userInfo.getPassword().equals(EncryptUtilsV2.MD5Encode(password))){
			map.put("code", 0);
			map.put("message", "密码错误");
			return map;
		}
		if(userInfo.getStatus() !=0 ){
			map.put("code", 0);
			map.put("message", "用户被冻结，请联系管理员");
			return map;
		}
		map.put("code", 200);
		map.put("message", "登录成功");
		return map;
	}
	
	/**
	 * 重置密码
	 * @param model
	 * @param user
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("resetPassword")
	@ResponseBody
	public Map<String, Object> resetPassword(Model model, @ModelAttribute UserInfo user,
			HttpServletRequest request) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		String mobile = user.getMobile();
		String password = user.getPassword();
		String verifyCode = user.getVerifyCode();
		HttpSession session = request.getSession(true);
		String verifyCodeSession = session.getAttribute("rand") == null ? "" : session.getAttribute("rand").toString();
		String sms_code_message = Constants.USER_MESSAGE.get(mobile);
		if (!verifyCode.equalsIgnoreCase(verifyCodeSession)) {
			map.put("code", 0);
			map.put("message", "验证码不正确，请重新输入");
			return map;
		}
		if (!StringUtils.hasText(sms_code_message)) {
			map.put("code", 0);
			map.put("message", "短信验证码已经过期，请重新输入");
			return map;
		}
		UserInfo userInfo = new UserInfo();
		userInfo.setMobile(mobile);
		userInfo = userInfoService.selectUserInfo(userInfo);
		UserInfo userInfo1 = new UserInfo();
		userInfo1.setId(userInfo.getId());
		userInfo1.setPassword(EncryptUtilsV2.MD5Encode(password));
		int updateCount = userInfoService.updateUserInfo(userInfo1);
		if(updateCount > 0) {
			map.put("code", 200);
			map.put("message", "重置密码成功");
		} else {
			map.put("code", 0);
			map.put("message", "重置密码失败");
		}
		Constants.USER_MESSAGE.clear();
		return map;
	}

}
